package com.beaut.project.sms;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.dbcp.BasicDataSource;


import com.beaut.project.util.SMSUtil;
import com.beaut.project.util.SpringContextUtil;
import com.beaut.project.util.Utility;

import nl.justobjects.pushlet.core.Dispatcher;
import nl.justobjects.pushlet.core.Event;
import nl.justobjects.pushlet.core.Session;
import nl.justobjects.pushlet.core.SessionManager;

public class SessionPushletManage {
	static SessionPushletManage sessionPush=null;
	private SessionPushletManage(){
		
	}
	
	public static SessionPushletManage getInstance(){
		if(sessionPush==null)
			sessionPush=new SessionPushletManage();
		return sessionPush;
	}
	 public void myUnicast()  
	    {  
		  PreparedStatement ps = null;
		    ResultSet rs = null;
		Object ds=    SpringContextUtil.getBean("dataSource");
		if(ds==null) return;
		 BasicDataSource dataSource=(BasicDataSource) ds;
		 Connection con=null;
		   try {
			 con= dataSource.getConnection();
			
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		 if(SessionManager.getInstance()==null)
			 return;
		 List<Map<String,Object>> l=new ArrayList<Map<String,Object>>();
		int count= SessionManager.getInstance().getSessionCount();
		Session[] s=SessionManager.getInstance().getSessions();
		int noRead=0;
		for(int j=0;j<count;j++){
			 try{
				 
			      String sql = "select s.*,u.truename from (select * from sms_manage  where recieve_user_id='"+s[j].getId()+"' and is_send=0 order by create_time desc limit 1) as s left join user as u on s.create_user_id=u.id";
			     String createTime=Utility.getCurDateTimeStr();
			      ps = con.prepareStatement(sql);
			      rs = ps.executeQuery();
			      
			      if (rs.next()){
			    	  Map<String,Object> m = new HashMap<String,Object>();
			    	  m.put("sms_title", rs.getString("sms_title").replace(" ", "&nbsp;"));
			    	  createTime=rs.getString("create_time");
			    	  m.put("create_time", createTime.replace(" ", "&nbsp;"));
			    	  if("-1".equals(rs.getString("create_user_id"))){
			    		  m.put("truename", "系统提醒");
			    	  }else{
			    		  m.put("truename", rs.getString("truename"));
			    	  }
			    	  l.add(m);
			      }
//			      else{
//			    	  continue;
//			      }
			      String sql2="update sms_manage set is_send=1,send_time='"+Utility.getCurDateTimeStr()+"' where recieve_user_id='"+s[j].getId()+"' and create_time<='"+createTime+"'";
			      ps.executeUpdate(sql2);
			      //查询未读消息
			     
			      String sql3 = "select count(id) from  sms_manage  where recieve_user_id='"+s[j].getId()+"' and is_read=0";
			      ps = con.prepareStatement(sql3);
			      rs=  ps.executeQuery();
			      if(rs.next()){
			    	  noRead=rs.getInt(1);
			      }
			    } catch (Exception e) {
			      e.printStackTrace();
			    } finally{
//			    	SMSUtil.close(ps, rs, null);
//			    	SMSUtil.closeDbConn(con, null);
			    }
            Event  event = Event.createDataEvent("myevent1");   
            try {
				event.setField("key1", URLEncoder.encode(Utility.lstMaptoJson(l),"UTF-8"));
				event.setField("key2", noRead);
			} catch (UnsupportedEncodingException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}            
            Dispatcher.getInstance().unicast(event,s[j].getId()); //向ID为piero的用户推送  

//            System.out.println("success....");  
		}
 
        SMSUtil.close(ps, rs, null);
    	SMSUtil.closeDbConn(con, null);
	  
	  
	    }  
	    private void myMulticast()  
	    {  
	        Event  event = Event.createDataEvent("myevent1");   
	        event.setField("key1", "houhou....");    
	        Dispatcher.getInstance().multicast(event);  //向所有和myevent1名称匹配的事件推送  
	          
	        System.out.println("wa success....");  
	    }  
	    private void myBroadcast()  
	    {  
	        Event  event = Event.createDataEvent("myevent1"); //向所有的事件推送，不要求和这儿的myevent1名称匹配  
	        event.setField("key1", "dig hole....");      
	        Dispatcher.getInstance().broadcast(event);  
	          
	        System.out.println("asw success....");  
	    }  
}
